﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Windows.Forms;
using Microsoft.WindowsServerSolutions.Administration.ObjectModel;
using Microsoft.WindowsServerSolutions.Administration.ObjectModel.ComponentServices;
using TV4Home.Server.TVEInteractionLibrary.Interfaces;
using TV4Home.Server.Vail.AddIn.TunersAndStreamingClients;

namespace TV4Home.Server.Vail.AddIn
{
    public class TunersAndStreamingClientsSubTabPage : Page
    {
        public TunersAndStreamingClientsSubTabPage()
            : base(new Guid("F02098FA-D1F8-45FB-A49F-6B7A1F8941E5"),
            "Tuners / Streaming Clients",
            "View installed tuners and streaming clients.")
        {
        }

        protected override PageContent CreateContent()
        {
            return PageContent.Create<MyBusinessObject>(
               new SubTabListProvider(this),
               SubTabListColumns.CreateColumns(),
               SubTabListGroupings.CreateGroupings(),
               SubTabTasks.CreateTasks(),
               SubTabDetails.GetDetails
            );
        }
    }

    namespace TunersAndStreamingClients
    {
        public class MyBusinessObject
        {
            public MyBusinessObject(object item)
            {
                this.Item = item;
            }

            private object Item { get; set; }

            public WebCard Card { get { return this.Item as WebCard; } }
            public WebRtspClient RtspClient { get { return this.Item as WebRtspClient; } }

            public bool IsWebCard
            {
                get { return this.Item is WebCard; }
            }

            public bool IsWebRtspClient
            {
                get { return this.Item is WebRtspClient; }
            }
        }

        public class SubTabListProvider : ListProvider<MyBusinessObject>
        {
            ITVEInteraction wcfChannel = null;

            public SubTabListProvider(IServiceProvider serviceProvider)
            {
                SubTabTasks.serviceProvider = serviceProvider;
            }

            protected override void RefreshAndListenForUpdates(IList<MyBusinessObject> list)
            {
                try
                {
                    this.Errors.Reset();

                    if (wcfChannel == null)
                        wcfChannel = ChannelFactory<ITVEInteraction>.CreateChannel(new NetNamedPipeBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress("net.pipe://localhost/TV4Home.Server.CoreService/TVEInteractionService"));
                    
                    foreach (WebCard card in wcfChannel.GetCards())
                    {
                        list.Add(new MyBusinessObject(card));
                    }

                    foreach (WebRtspClient client in wcfChannel.GetStreamingClients())
                    {
                        list.Add(new MyBusinessObject(client));
                    }
                }
                catch (Exception ex)
                {
                    this.Errors.Report(new ErrorInfo("Couldn't retrieve data.", ex));

                    if (ex.InnerException != null)
                        this.Errors.Report(new ErrorInfo("InnerException", ex.InnerException));

                    wcfChannel = null;
                }
            }

            protected override void StopListeningForUpdates()
            {

            }

            protected override string GetObjectDisplayName(MyBusinessObject businessObj)
            {
                return businessObj.IsWebCard ? businessObj.Card.Name : businessObj.RtspClient.IpAdress;
            }

            protected override string GetObjectId(MyBusinessObject businessObj)
            {
                return businessObj.IsWebCard ? businessObj.Card.IdCard.ToString() : businessObj.RtspClient.IpAdress;
            }

            protected override System.Drawing.Icon GetObjectIcon(MyBusinessObject businessObj)
            {
                return businessObj.IsWebCard ? Properties.Resources.Tuner : Properties.Resources.Client;
            }
        }

        static class SubTabListColumns
        {
            public static ListColumnCollection<MyBusinessObject> CreateColumns()
            {
                return new ListColumnCollection<MyBusinessObject>()
                           {
                               new ListColumn<MyBusinessObject>("Name", x => x.IsWebCard ? x.Card.Name : x.RtspClient.IpAdress)
                                   {
                                       IsRequired = true,
                                       IconProvider = x => x.IsWebCard ? Properties.Resources.Tuner : Properties.Resources.Client
                                   }
                           };
            }
        }

        static class SubTabListGroupings
        {
            public static ListGroupingCollection<MyBusinessObject> CreateGroupings()
            {
                ListGroupingCollection<MyBusinessObject> groupCollection =
                    new ListGroupingCollection<MyBusinessObject>()
                        {
                            new ListGrouping<MyBusinessObject>("Tuners / Streaming Clients", x => x.IsWebCard ? new ListGroup<MyBusinessObject>("Tuners") : new ListGroup<MyBusinessObject>("Streaming Clients"))
                        };

                groupCollection.DefaultGrouping = groupCollection.First<ListGrouping<MyBusinessObject>>();

                return groupCollection;
            }
        }

        static class SubTabTasks
        {
            public static IServiceProvider serviceProvider;

            public static TaskCollection CreateTasks()
            {
                return new TaskCollection
                           {
                               RefreshTask()
                           };
            }

            private static AsyncUiTask RefreshTask()
            {
                return new AsyncUiTask("Refresh", sender =>
                {
                    DoRefresh();
                    return null;
                });
            }

            private static void DoRefresh()
            {
                if (serviceProvider == null)
                    return;

                DataRefresher service = serviceProvider.GetService(typeof(DataRefresher)) as DataRefresher;

                if (service != null)
                    service.Refresh();
            }
        }

        static class SubTabDetails
        {
            public static DateTime DateTimeMin = new DateTime(2000, 1, 1);

            public static DetailColumnCollection GetDetails(MyBusinessObject businessObj)
            {
                DetailColumnCollection columns = new DetailColumnCollection();
                DetailColumn column = new DetailColumn();

                DetailGroup group = null;

                if (businessObj.IsWebCard)
                {
                    group = new DetailGroup("Tuner Information")
                                {
                                    {"Name", businessObj.Card.Name},
                                    {"Device Path", businessObj.Card.DevicePath},
                                    {"Enabled", businessObj.Card.Enabled.ToString()},
                                    {"Grab EPG", businessObj.Card.GrabEPG.ToString()},
                                    {"Last EPG grab", businessObj.Card.LastEpgGrab != DateTimeMin ? businessObj.Card.LastEpgGrab.ToString() : ""},
                                    {"Has CAM", businessObj.Card.CAM.ToString()},
                                    {"Supports Subchannels", businessObj.Card.supportSubChannels.ToString()},
                                    {"Recording folder ", businessObj.Card.RecordingFolder},
                                    {"Timeshift folder ", businessObj.Card.TimeShiftFolder}
                                };
                }
                else
                {
                    group = new DetailGroup("Streaming Client Information")
                                {
                                    {"Name", businessObj.RtspClient.IpAdress},
                                    {"Description", businessObj.RtspClient.Description},
                                    {"Stream Name", businessObj.RtspClient.StreamName},
                                    {"Started", businessObj.RtspClient.DateTimeStarted.ToString()},
                                    {"Is Active", businessObj.RtspClient.IsActive.ToString()}
                                };
                }

                column.Add(group);
                columns.Add(column);

                return columns;
            }
        }
    }
}